<?php
namespace app\controller;

use app\BaseController;
// use app\controller\ForwardController;
use app\middleware\Auth;
use app\model\Elevator;
use app\model\ElevatorAlarmNdata;
use app\model\ElevatorAlarmRdata;
use app\model\ElevatorNdata;
use app\model\ElevatorRdata;
use app\model\ElevatorWorkData;
use app\model\Project;
use app\model\User;
use GuzzleHttp\Client;
use think\facade\Log;
use think\Request;

//use think\facade\Db;
/* 塔机设备控制器 */

class ElevatorController extends BaseController
{
    /* 控制器私有变量 */
    private $alarm_array = ['正常', '高度预警', '高度报警', '重量预警', '重量报警', '负荷预警', '负荷报警', '风速预警', '风速报警', '倾角预警', '倾角报警', '速度预警', '速度报警']; //报警数据字典
    protected $middleware = [Auth::class]; //控制器中间件

    /* 设备接口 */
    public function elevatorInfo(Request $request)
    {
        $where = [];
        if ($request->has('mac')) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $equipment = Elevator::where($where)->find();
        if ($equipment) {
            return success($equipment);
        } else {
            return fail(null, '设备ID不存在', 0);
        }
    }
    //添加循环吊次数据
    public function elevatorWorkData(Request $request)
    {
        $workdata = new ElevatorWorkData;
        $data = $request->post();

        foreach ($data as $key => $value) {
            if (is_double($value)) {
                $value = round($value, 2);
            }
            $workdata->$key = $value;
        }
        // Log::write($workdata, 'elevatorWorkData');
        //循环吊次转发
        $eid = [22100055, 22100060];
        if (in_array($data['eid'], $eid)) {
            $url = 'http://183.213.16.9:9002/iotZongyiyuan/v2/iot/dtcloud/elevator2';
            $send['eid'] = $data['eid'];
            $send['startheight'] = $data['start_height'];
            $send['endheight'] = $data['end_height'];
            $send['avgspeed'] = $data['speed'];
            $send['maxxtilt'] = $data['end_tilt_x'];
            $send['maxytilt'] = $data['end_tilt_y'];
            $send['uploaddate'] = date('Y-m-d H:i:s', time());
            $send['begindate'] = $data['start_time'];
            $send['enddate'] = $data['end_time'];
            $send['weight'] = $data['weight'];
            $client = new Client;
            $response = $client->request('POST', $url, [
                'json' => $send,
            ])->getBody();
            $stringBody = (string) $response;
            // Log::write($stringBody, 'elevatorWorkData');
        }
        $eid4 = [23080202];
        if (in_array($data['eid'], $eid4)) {
            $url = 'http://123.60.57.233:8082/ayy/api/cyclic';
            $send['deviceId'] = (int) $data['eid'];
            $send['deviceType'] = 'elevator';
            $send['maxWeight'] = $data['weight'];
            $send['startTime'] = $data['start_time'];
            $send['endTime'] = $data['end_time'];
            $send['startHeight'] = $data['start_height'];
            $send['endHeight'] = $data['end_height'];
            $send['maxSpeed'] = $data['speed'];
            $send['maxPerson'] = $data['number'];
            $send['maxDipangleX'] = $data['end_tilt_x'];
            $send['maxDipangleY'] = $data['end_tilt_y'];
            $send['maxWindSpeed'] = 0;
            $send['sendTime'] = date('Y-m-d H:i:s', time());
            //-----未提供
            // $send['idCard'] = '--';
            $client = new Client;
            $response = $client->request('POST', $url, [
                'json' => $send,
            ])->getBody();
            $stringBody = (string) $response;
            Log::write($send, 'ForwardController225');
            Log::write($stringBody, 'ForwardController225');
        }
        $eid2 = [22040007, 22040009, 22090049, 22090044, 22100063, 22100064];
        if (in_array($data['eid'], $eid2)) {
            $url = 'https://zhgd.fjuj.com.cn/v1/iot/elevator4tanyue/elevatorWorkData';
            $client = new Client;
            $response = $client->request('POST', $url, [
                'json' => $data,
            ])->getBody();
            $stringBody = (string) $response;
            Log::write($data, 'elevatorWorkData');
            Log::write($stringBody, 'elevatorWorkData');
        }
        $eid3 = [22110092, 22110101, 22110086, 22110093, 23030117];
        if (in_array($data['eid'], $eid3)) {
            $url = 'http://221.0.183.26:9880/api/ty/elevator/workData';
            $data['weight'] = rand(1, 200);
            $client = new Client;
            $response = $client->request('POST', $url, [
                'json' => $data,
            ])->getBody();
            $stringBody = (string) $response;
            // Log::write($data, 'elevatorWorkData');
            // Log::write($stringBody, 'elevatorWorkData');
        }
        $eid5 = [23090237, 23090248, 23090251, 23090250, 23090238, 23090245, 23080180, 23090216,23120431,23120426,23120450,23120429,23120447,23120443,23120427,23120424,23120436,23120441,23090227,23090231,23090220,23090260,23090219,23090247,23090246,23090229,23080215,23090236,23090262,23080181,23120461,23120459,23120422,23080167,23110420];
        if (in_array($data['eid'], $eid5)) {
            //小袁--苏州客户 筑安--升降机
            $param = $data;
            $url = 'http://material-api.huariot.com/';
            $key = 'sdtanyue001';
            $secret = '351E477205994EF48606B0E5475CE4E0';
            $getTokenUrl = 'api-gateway/api/third/v1/auth/login/';
            $token_url = $url . $getTokenUrl . '?' . 'key=' . $key . '&secret=' . $secret;
            $client = new Client;
            $response = $client->request('GET', $token_url)->getBody();
            $stringBody = json_decode((string) $response);
            $accessToken = $stringBody->data->accessToken;
            /* 设备上线 */
            $id = ElevatorNdata::where('eid', $param['eid'])->value('other');
            /* 实时数据添加 */
            $dataUrl = $url . 'device-socket/api/v1/third/elevator/work-data/';
            /*
            {
            "oblique_warn_status": 0,
            "overspeed_warn_status": 0,
            "wight_warn_status": 0,
            "source_id": 3502814
            }
             */
            $send = [
                "id" => $id,
                "index" => $param['eid'],
                "run_start_time" => strtotime($data['start_time']) * 1000,
                "run_end_time" => strtotime($data['end_time']) * 1000,
                "start_height" => $param['start_height'],
                "speed" => $param['speed'],
                "height" => $param['start_height'],
                "end_height" => $param['end_height'],
                "load_value" => $param['weight'],
                "number_of_people" => $param['number'],
                "angle" => $param['start_tilt_x'],
                "angle2" => $param['start_tilt_y'],
                "work_status" => 0,
                "percent_rate" => 0,
                "gprs_online" => 1,
                "running_state" => 1,
                "warn_flag" => false,
                "display_request_code" => 1,
                "collection_time" => time() * 1000,
            ];
            $send_json = json_encode($send);
            $client = new Client;
            $response = $client->request('POST', $dataUrl, [
                'json' => $send,
                'headers' => [
                    'Authorization' => 'Bearer ' . $accessToken,
                ],
            ])->getBody();
            $stringBody = (string) $response;
            // Log::write($send_json, 'ForwardController227');
            // Log::write($stringBody, 'ForwardController227');
        }
        $eid6 = [23100299];
        if (in_array($data['eid'], $eid6)) {
            //江苏傲之途
            $url = 'http://device.aozhitu.cn:8000/api/device/deviceLifters/cycle';

            $secretId = 'W5nzlv5VLYIuDllY5MzaMploLEQTFVPTuYYf';
            $secretKey = 'xDcfbj9KervlVwee8rHvpvMQqv0g5ROzMV65';
            $Timestamp = time() * 1000;
            $Nonce = rand(10000, 99999);
            $str = 'SecretId=' . $secretId . '&X-Nonce=' . $Nonce . '&X-Timestamp=' . $Timestamp;
            $hash_hmac = base64_encode(hash_hmac("sha1", $str, $secretKey, true));
            $send = [
                "sn" => $data['eid'],
                "gradientX" => round($data['start_tilt_x'], 2),
                "height" => $data['end_height'],
                "startDate" => strtotime($data['start_time']) * 1000,
                "date" => date('Y-m-d H:i:s', time()),
                "gradientY" => round($data['start_tilt_y'], 2),
                "direction" => "UP",
                "startHeight" => $data['start_height'],
                "loadPercent" => 0,
                "endHeight" => $data['end_height'],
                "endDate" => strtotime($data['end_time']) * 1000,
                "averageSpeed" => round($data['speed'], 2),
                "load" => $data['weight'],
            ];
            $json = json_encode($send);
            $send_json = json_encode($send);
            $client = new Client;
            /* url_basic send_basic */
            $response = $client->request('POST', $url, [
                'json' => $send,
                'headers' => [
                    'X-Timestamp' => $Timestamp,
                    'X-Nonce' => $Nonce,
                    'SecretId' => $secretId,
                    'X-Signature' => $hash_hmac,
                    'Sn' => $data['eid'],
                ],
            ])->getBody();
            $stringBody = (string) $response;
            Log::write($send_json, 'ForwardController232');
            Log::write($stringBody, 'ForwardController232');
        }
        $eid7 = [23060161];//福建测试
        if (in_array($data['eid'], $eid7)) {
            $param = $data;
            $url = '101.133.149.245:9999/wd/lifter/addLiftCirculation';
            $client = new Client;
            $param['eid'] = (int) $param['eid'];
            $response = $client->request('POST', $url, [
                'json' => $param,
            ])->getBody();
            $stringBody = (string) $response;
            // Log::write($param, 'ForwardController_236');
            // Log::write($stringBody, 'ForwardController_236');
        }
        $eid8 = [23110323,23110328,23110324,23110331,23110325,23110330,23110327,23110326,23110329];//福建测试
        if (in_array($data['eid'], $eid8)) {
            $param = $data;
            $url = 'https://openapi.anculsai.com:8004/open/api/v1/fse/lift/anon/tanyue/workData';
            $client = new Client;
            foreach ($param as $key => $value) {
                $param[$key] = round($param[$key], 2);
            }
            $param['eid'] = (int) $param['eid'];
            $response = $client->request('POST', $url, [
                'json' => $param,
            ])->getBody();
            $stringBody = (string) $response;
            Log::write($param, 'ForwardController_237');
            Log::write($stringBody, 'ForwardController_237');
        }
        $rq = $workdata->save();
        return success($rq);
    }
    //设备更新信息
    public function updateElevatorEquipment()
    {
        $request = $this->request->param();
        // Log::write($request, 'updateElevatorEquipment');
        $equipment = Elevator::where('eid', $request['eid'])->find();
        if (!$equipment) {
            return fail(null, '设备ID不存在', 0);
        }

        foreach ($request as $key => $value) {
            $equipment->$key = $value;
        }
        $re = $equipment->save();
        if ($re) {
            // if ($this->request->has('online')) {
            //     $online['online'] = $equipment->online;
            //     return success($online);
            // }
            return success($equipment);
        } else {
            return fail(null, '无内容', 0);
        }
    }
    /* 平台接口 */
    public function elevatorList(Request $request)
    {
        $user = $request->user;

        $where = [];
        if ($request->has('ename', 'get', true)) {
            $ename = $request->param('ename');
            $where[] = ['ename', 'like', '%' . $ename . '%'];
        }
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', 'like', '%' . $eid . '%'];
        }
        if ($request->has('mac', 'get', true)) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }
        if ($request->has('pid', 'get', true)) {
            $pid = $request->param('pid');
            $where[] = ['pid', '=', $pid];
        }

        if ($user->identity == 'user') {
            $uid = $user->id;
            $where[] = ['uid', '=', $uid];
        } elseif ($user->identity == 'sale') {
            $belong_id = $user->id;
            $users = User::where('belong_id', $belong_id)->column('id');
            $where[] = ['uid', 'in', $users];
        }
        $equipment = Elevator::where($where)->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        /* 禁用轮询--添加额外信息 */
        $userList = User::select()->toArray();
        $projectList = Project::select()->toArray();
        $name = array_column($userList, 'name', 'id');
        $username = array_column($userList, 'username', 'id');
        $pname = array_column($projectList, 'pname', 'id');
        //增加额外数据
        foreach ($equipment as $key => $value) {
            if ($value->uid == 0 || $value->pid == 0) {
                $value->uname = '';
                $value->username = '';
                $value->pname = '';
            } else {
                $value->uname = $name[$value->uid];
                $value->username = $username[$value->uid];
                $value->pname = $pname[$value->pid];
            }

        }
        if ($request->has('pname', 'get', true)) {
            $pname = $request->param('pname');
            $equipment = $equipment->where('pname', 'like', $pname);
        }
        if ($request->has('username', 'get', true)) {
            $username = $request->param('username');
            $equipment = $equipment->where('username', 'like', $username);
        }

        return pageReturn($equipment);
    }
    /* 历史数据&实时数据 */
    public function elevatorCraneRdata(Request $request)
    {
        $where = [];
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
            $list = ElevatorRdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
            return pageReturn($list);
        } else {
            return fail(null, '缺少必要参数');
        }

    }
    public function elevatorCraneNdata(Request $request)
    {
        $where = [];
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $data_one = ElevatorNdata::where($where)->find();
        return success($data_one);
    }
    /* 报警数据相关 */
    public function elevatorAlarmRdata(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        if ($request->has('mac', 'get', true)) {
            $mac = $request->param('mac');
            $where[] = ['mac', 'like', '%' . $mac . '%'];
        }
        if ($request->has('create_time', 'get', true)) {
            $create_time = $request->param('create_time');
            $where[] = ['create_time', '>=', $create_time[0]];
            $where[] = ['create_time', '<=', $create_time[1]];
        }
        if ($request->user->identity == 'user') {
            $uid = $user->id;
            $where[] = ['uid', '=', $uid];
        } elseif ($request->user->identity == 'sale') {
            $belong_id = $user->id;
            $users = User::where('belong_id', $belong_id)->column('id');
            $eids = Elevator::where('uid', 'in', $users)->column('eid');
            $where[] = ['eid', 'in', $eids];
            $list = ElevatorAlarmNdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
            /* 禁用轮询--添加额外信息 */
            $userList = User::select()->toArray();
            $projectList = Project::select()->toArray();
            $towerList = Elevator::select()->toArray();

            $username = array_column($userList, 'username', 'id');
            $pname = array_column($projectList, 'pname', 'id');
            $ename = array_column($towerList, 'ename', 'eid');
            $pids = array_column($towerList, 'pid', 'eid');
            $uids = array_column($towerList, 'uid', 'eid');
            //增加额外数据
            foreach ($list as $key => $value) {
                if ($value->eid == 0) {
                    $value->ename = '';
                    $value->pname = '';
                    $value->username = '';
                } else {
                    $value->ename = $ename[$value->eid];
                    $pid = $pids[$value->eid];
                    $uid = $uids[$value->eid];
                    $value->pname = $pname[$pid];
                    $value->username = $username[$uid];
                }

            }
            if ($request->has('pname', 'get', true)) {
                $pname = $request->param('pname');
                $list = $list->where('pname', 'like', $pname);
            }
            if ($request->has('username', 'get', true)) {
                $username = $request->param('username');
                $list = $list->where('username', 'like', $username);
            }
            return pageReturn($list);
        }
        $list = ElevatorAlarmRdata::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);

    }
    public function elevatorAlarmNdata(Request $request)
    {
        $where = [];
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        $data_one = ElevatorAlarmNdata::where($where)->find();
        return success($data_one);
    }
    /* 升降机循环数据 */
    public function elevatorWorkDataList(Request $request)
    {
        $where = [];
        if ($request->has('eid', 'get', true)) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        }
        if ($request->has('create_time', 'get', true)) {
            $create_time = $request->param('create_time');
            $where[] = ['create_time', '>=', $create_time[0]];
            $where[] = ['create_time', '<=', $create_time[1]];
        }
        $list = ElevatorWorkData::where($where)->order('id desc')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($list);

    }
}
